package com.szl.yeb.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yeb
 * @description: JwtToken工具类
 * @author: szl
 * @create: 2022-08-24 18:28
 **/
@Component
public class JwtTokenUtil {
    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;


    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", userDetails.getUsername());
        claims.put("created", new Date());
        return generateTokenFromClaims(claims);
    }

    public String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();

    }

    public Boolean isTokenEffective(String token, UserDetails userDetails) {
        String usernameFromToken = getUsernameFromToken(token);
        String username = userDetails.getUsername();
        Boolean tokenNotExpired = isTokenNotExpired(token);
        return username.equals(usernameFromToken) && tokenNotExpired;
    }

    public String reFreshToken(String token) {
        Claims claimsFromToken = getClaimsFromToken(token);
        claimsFromToken.setExpiration(generateExpiration());
        return generateTokenFromClaims(claimsFromToken);
    }

    private Boolean isTokenNotExpired(String token) {
        return new Date().before(getExpirationFromToken(token));
    }

    private Date getExpirationFromToken(String token) {
        return getClaimsFromToken(token).getExpiration();
    }

    private Claims getClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    private String generateTokenFromClaims(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .setExpiration(generateExpiration())
                .compact();
    }

    private Date generateExpiration() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

}
